<?php

/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms

$Id: index.php 843 2008-12-05 08:02:58Z zhaoxiongfei $
*/

error_reporting(E_ERROR | E_PARSE);
@set_time_limit(1000);
set_magic_quotes_runtime(0);

define('IN_COMSENZ', TRUE);
define('UC_API', TRUE);
define('ROOT_PATH', dirname(__FILE__).'/../');

require ROOT_PATH.'./install/var.inc.php';
require ROOT_PATH.'./install/lang.inc.php';
require ROOT_PATH.'./install/db.class.php';
require ROOT_PATH.'./install/func.inc.php';

file_exists(ROOT_PATH.'./install/extvar.inc.php') && require ROOT_PATH.'./install/extvar.inc.php';

$view_off = getgpc('view_off');

define('VIEW_OFF', $view_off ? TRUE : FALSE);

$allow_method = array('show_license', 'env_check', 'uc_init', 'db_init', 'ext_info', 'install_check', 'tablepre_check');

$step = intval(getgpc('step', 'R')) ? intval(getgpc('step', 'R')) : 0;
$method = getgpc('method');

if(empty($method) || !in_array($method, $allow_method)) {
	$method = isset($allow_method[$step]) ? $allow_method[$step] : '';
}

if(empty($method)) {
	show_msg('method_undefined', $method, 0);
}

if(!ini_get('short_open_tag')) {
	show_msg('short_open_tag_invalid', '', 0);
} elseif(file_exists($lockfile)) {
	show_msg('install_locked', '', 0);
} elseif(!class_exists('dbstuff')) {
	show_msg('database_nonexistence', '', 0);
}

if($method == 'show_license') {

	show_license();

} elseif($method == 'env_check') {

	VIEW_OFF && function_check($func_items);

	env_check($env_items);

	dirfile_check($dirfile_items);

	show_env_result($env_items, $dirfile_items, $func_items);
	
	
} elseif($method == 'uc_init') {	

//UCenter配置

	if(isset($_POST['ucsubmit'])){
		$ucapi = preg_replace("/\/$/", '', trim($_POST['ucapi']));
		$ucip = trim($_POST['ucip']);
		if(!@include_once ROOT_PATH.'./uc_client/client.php') {
			show_msg('uc_client目录不存在','', 0);
		}
		
		$ucinfo = dfopen($ucapi.'/index.php?m=app&a=ucinfo&release='.UC_CLIENT_RELEASE, 500, '', '', 1, $ucip);
		list($status, $ucversion, $ucrelease, $uccharset, $ucdbcharset, $apptypes) = explode('|', $ucinfo);
		if($status != 'UC_STATUS_OK') {
			show_msg('UCenter无法正常连接，返回错误 ( $status )','', 0);
		}else{
		$tagtemplates = '';
		$uri = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
		$app_url = strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/'))).'://'.$_SERVER['HTTP_HOST'].substr($uri, 0, strrpos($uri, '/install/'));
		$app_name = trim($_POST['sitename']);
		$postdata = "m=app&a=add&ucfounder=&ucfounderpw=".urlencode($_POST['ucfounderpw'])."&apptype=".urlencode('OTHER')."&appname=".urlencode($app_name)."&appurl=".urlencode($app_url)."&appip=&appcharset=gbk".'&appdbcharset=gbk'.'&release='.UC_CLIENT_RELEASE.'&'.$tagtemplates;
		$s = dfopen($ucapi.'/index.php', 500, $postdata, '', 1, $ucip);
			if(empty($s)) {
				show_msg('UCenter用户中心无法连接','', 0);
			} elseif($s == '-1') {
				show_msg('UCenter管理员帐号密码不正确','', 0);
			} else {
				$ucs = explode('|', $s);
				if(empty($ucs[0]) || empty($ucs[1])) {
					show_msg('UCenter返回的数据出现问题，请参考:<br />'.shtmlspecialchars($s));
				}else {

					if(save_uc_config($s."|$ucapi|$ucip", CONFIG)){
			show_header();
			print<<<END
			<form id="theform" method="get" action="?step=3">
			<table>
			<tr><td>UCenter注册成功！当前程序ID标识为: $ucs[1]</td></tr>
			</table>

			<table class=button>
			<tr><td>
			<input type=hidden name=step value=3>
			<input type="submit" id="uc2submit" name="uc2submit"  value="进入下一步"></td></tr>
			</table>
			</form>
END;
			show_footer();
					
					
					
					}
					
					

					
				}
			
			}
		
		}
		

	}

show_header();
$ucapi = "http://";

		print<<<END
		<form id="theform" method="post" action="$theurl">
		<div>
			<table class="showtable">
				<tr><td><strong># 请填写 UCenter 的相关参数</strong></td></tr>
				$plus
			</table>
			<br>
			<p style="font-weight:bold;">请输入已安装UCenter的信息:</p>
END;
	print<<<END
		<table class=datatable>
			<tbody>
				<tr height=60>
					<td>UCenter 的URL:</td>
					<td><input type="text" id="ucapi" name="ucapi" size="60" value="$ucapi"><br>例如：http://www.discuz.net/ucenter</td>
				</tr>
				<tr height=60>
					<td>UCenter 的创始人密码:</td>
					<td><input type="password" id="ucfounderpw" name="ucfounderpw" size="20" value="$ucfounderpw"></td>
				</tr>
			</tbody>
		</table>
		<p style="font-weight:bold;">请填写站点信息:</p>
		<table class="datatable">
			<tbody>
				<tr height=60>
					<td width="26%"> 站点名称:</td>
					<td><input type="text" class="txt" size="20" value="团购系统" name="sitename"/></td>
				</tr>
			</tbody>
		</table>
	</div>

	<table class=button>
	<tr><td><input type="submit" id="ucsubmit" name="ucsubmit" value="提交UCenter配置信息"><input type="button" id="" name="submit" onclick="window.location='index.php?step=3'" value="跳过不设置ucenter"></td></tr>
	</table>
	<input type="hidden" id="ucfounder" name="ucfounder" size="20" value="">
	<input type="hidden" name="formhash" value="$formhash">
	</form>
END;


show_footer();



} elseif($method == 'db_init') {

	@include CONFIG;
	$submit = true;
	$error_msg = array();
	if(isset($form_db_init_items) && is_array($form_db_init_items)) {
		foreach($form_db_init_items as $key => $items) {
			$$key = getgpc($key, 'p');
			if(!isset($$key) || !is_array($$key)) {
				$submit = false;
				break;
			}
			foreach($items as $k => $v) {
				$tmp = $$key;
				$$k = $tmp[$k];
				if(empty($$k) || !preg_match($v['reg'], $$k)) {
					if(empty($$k) && !$v['required']) {
						continue;
					}
					$submit = false;
					VIEW_OFF or $error_msg[$key][$k] = 1;
				}
			}
		}
	} else {
		$submit = false;
	}
	
	
	
	if(!VIEW_OFF && $_SERVER['REQUEST_METHOD'] == 'POST') {
	
		if($adminpw != $adminpw2) {
			$error_msg['admininfo']['ucfounderpw2'] = 1;
			
			
			
			$submit = false;
		}

		$forceinstall = isset($_POST['dbinfo']['forceinstall']) ? $_POST['dbinfo']['forceinstall'] : '';
		$dbname_not_exists = true;
		if(!empty($dbhost) && empty($forceinstall)) {
			$dbname_not_exists = check_db($dbhost, $dbuser, $dbpw, $dbname, $tablepre);
			if(!$dbname_not_exists) {
				$form_db_init_items['dbinfo']['forceinstall'] = array('type' => 'checkbox', 'required' => 0, 'reg' => '/^.*+/');
				$error_msg['dbinfo']['forceinstall'] = 1;
				$submit = false;
				$dbname_not_exists = false;
			}
		}
	}

	if($submit) {

		$step = $step + 1;
		if(empty($dbname)) {
			show_msg('dbname_invalid', $dbname, 0);
		} else {
			if(!@mysql_connect($dbhost, $dbuser, $dbpw)) {
				$errno = mysql_errno();
				$error = mysql_error();
				if($errno == 1045) {
					show_msg('database_errno_1045', $error, 0);
				} elseif($errno == 2003) {
					show_msg('database_errno_2003', $error, 0);
				} else {
					show_msg('database_connect_error', $error, 0);
				}
			}
			if(mysql_get_server_info() > '4.1') {
				mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname` DEFAULT CHARACTER SET ".DBCHARSET);
			} else {
				mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname`");
			}

			if(mysql_errno()) {
				show_msg('database_errno_1044', mysql_error(), 0);
			}
			mysql_close();
		}

		if(strpos($tablepre, '.') !== false || intval($tablepre{0})) {
			show_msg('tablepre_invalid', $tablepre, 0);
		}

		config_edit();

		$db = new dbstuff;
		$db->connect($dbhost, $dbuser, $dbpw, $dbname, DBCHARSET);

		$sql = file_get_contents($sqlfile);
		$sql = str_replace("\r\n", "\n", $sql);

		if(!VIEW_OFF) {
			show_header();
			show_install();
		}
		
		runquery($sql);
		$adminpwcode=md5(md5($adminpw));
		$timestr=time();
		//后台管理员
		$db->query("REPLACE INTO {$tablepre}admin (user,password,lastlogin,logincount,state) VALUES ('admin', '{$adminpwcode}','{$timestr}',0,1)");
		//$db->query("UPDATE {$tablepre}admin SET password ='{$adminpwcode}', nextrun='".($timestamp + 3600)."'");
		

		VIEW_OFF && show_msg('initdbresult_succ');

		if(!VIEW_OFF) {
			echo '<script type="text/javascript">document.getElementById("laststep").disabled=false;document.getElementById("laststep").value = \''.lang('install_succeed').'\';</script>'."\r\n";
			show_footer();
		}

	}
	if(VIEW_OFF) {

		show_msg('missing_parameter', '', 0);

	} else {

		show_form($form_db_init_items, $error_msg);

	}




} elseif($method == 'ext_info') {
	@touch($lockfile);
	@touch(ROOT_PATH.'./data/upgrade.lock');
	if(VIEW_OFF) {
		show_msg('ext_info_succ');
	} else {

		include CONFIG;
		$md5password =  UC_FOUNDERPW;
		setcookie('uc_founderauth', authcode("|$md5password|".md5($_SERVER['HTTP_USER_AGENT'])."|1", 'ENCODE', UC_KEY), time() + 3600, '/');
		header("Location:../admin");

	}

} elseif($method == 'install_check') {

	if(file_exists($lockfile)) {
		@touch(ROOT_PATH.'./data/upgrade.lock');
		show_msg('installstate_succ');
	} else {
		show_msg('lock_file_not_touch', $lockfile, 0);
	}

} elseif($method == 'tablepre_check') {

	$dbinfo = getgpc('dbinfo');
	extract($dbinfo);
	if(check_db($dbhost, $dbuser, $dbpw, $dbname, $tablepre)) {
		show_msg('tablepre_not_exists', 0);
	} else {
		show_msg('tablepre_exists', $tablepre, 0);
	}
}